<!--分配权限功能-->
<template>
  <el-dialog v-model="tagDialogVisible" title="分配权限" width="50%" @close="addArr" @open="open">
    <!--      树形控件-->
    <el-tree ref="treeRef" :data="tagList" :default-checked-keys="defKeys" :props="treeProps" default-expand-all
             node-key='id' show-checkbox></el-tree>
    <template #footer>
      <span class="dialog-footer">
      <el-button @click="tagDialogVisible= false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
    </template>
  </el-dialog>

</template>

<script>
import {request} from "../../../network/axios";
import {ElMessage} from "element-plus";

export default {
  name: "Dialog",
  created() {
    this.getTagData()
  },
  data() {
    return {
      tagList: [],
      tagDialogVisible: false,
      //树形控件的属性绑定
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中树形结构中的id值数组
      defKeys: [],
      pa: {
        rids: '',
        roleId: '',
      },
      node:''

    }
  },
  methods: {
    getTagData() {
      request({
        url: 'rights/tree'
      }).then(res => {
        if (res.status !== 200) ElMessage.error("获取权限失败")
        this.tagList = res.data.data
      })
    },
    //当对话框被打开
    open() {
      //获取三级节点的id
      this.roleId = this.$parent.rolesId
      this.node = this.$parent.nodes
      console.log(this.node)
      this.getLeafKeys(this.node, this.defKeys)
    },

    addArr() {
      this.defKeys = []
    },
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      this.rids = keys.join(',')
      request({
        url: `roles/${this.roleId}/rights`,
        method: 'post',
        data: this.pa
      }).then(res => {
        if (res.status !== 200) ElMessage.error("修改失败")
        console.log(res)
        ElMessage.success("修改成功")
        //关闭对话框
        this.tagDialogVisible = false
        //重新刷新
        this.getTagData()
      })
    },
    //通过递归的形式获取角色的三级节点并保存到defKeys中 ??
    getLeafKeys(role, arr) {
      //如果当前node不包含children则说明他是三级节点，把选中的id值放入到defKeys中
      if (!role.children) {
        return arr.push(role.id)
      }
      role.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
  }

}
</script>

<style scoped>

</style>